LATEX = latex
BIBTEX = bibtex

PDF = ps2pdf
PDF_FLAGS = -dMaxSubsetPct=100 -dCompatibilityLevel=1.2 -dSubsetFonts=true \
-dEmbedAllFonts=true  -dEPSCrop=true

PS = dvips
PS_FLAGS = -P cmz -t letter

WORKINGBASE = main
CAMERABASE = final

VERSIONNUMBER = $(shell hg tip --template '{date|hgdate}' | cut -f1 -d' ')

default: working

working: version $(WORKINGBASE).pdf

camera: $(CAMERABASE).pdf
	gs -q -dNOPAUSE -dBATCH -dPDFSETTINGS=/prepress -sDEVICE=pdfwrite -sOutputFile=$<.tmp $<
	mv $<.tmp $<

version:
	@echo "\\providecommand{\\\versionnumber}{$(VERSIONNUMBER)}" > version.tex

%.pdf: %.ps
	$(PDF) $(PDF_FLAGS) $< 

.PRECIOUS:%.ps
%.ps: %.dvi
	$(PS) $(PS_FLAGS) $< -o $@

$(WORKINGBASE).dvi: $(wildcard *.tex) $(wildcard *.bib) $(wildcard images/*.eps)
	$(LATEX) ${@:.dvi=}
	$(BIBTEX) ${@:.dvi=}
	$(LATEX) ${@:.dvi=}
	$(LATEX) ${@:.dvi=}

$(CAMERABASE).dvi: $(wildcard *.tex) $(wildcard *.bib) $(wildcard images/*.eps)
	$(LATEX) ${@:.dvi=}
	$(LATEX) ${@:.dvi=}
	$(LATEX) ${@:.dvi=}

clean:
	rm -rRf *.dvi *.aux *.blg *.log *.ps *~ *.bbl *.pdf *.out
